package wsepForum.network.common;

import java.nio.charset.Charset;


import com.thoughtworks.xstream.XStream;

/**
 * @author Oren Ben-Haim & Ariel Rozen
 *
 */
/**
 * Serialize and deserialize objects to raw data sent in network
 * @author Oren
 *
 */
public class RequestSerializer {

	/**
	 * Xstream for converting Objects to XML string
	 */
	private final static XStream xstream = new XStream();


	/**
	 * UTF-8 Charset
	 */
	private final static String DFL_CHARSET_STR = Charset.forName("UTF-8").toString();

	/*****************************
	 * MEMBERS                   *
	 *****************************/
	/**
	 * @param <T> object type
	 * @param request object to serialize
	 * @return raw data sent in network
	 */
	public static <T> String serialize(T request) {

		return Base64.encodeBytes(RequestSerializer.xstream.toXML(request).getBytes(), Base64.DONT_BREAK_LINES);

	}

	/**
	 * @param <T> object type
	 * @param coded  raw data sent in network
	 * @return object deserialized
	 */
	@SuppressWarnings("unchecked")
	public static <T> T deserialize(String coded) {
			byte[] decodedBytes = Base64.decode(coded);
			return (T)RequestSerializer.xstream.fromXML(fromBytes(decodedBytes, decodedBytes.length));
	}


	/**
	 * Convert bytes to string using encoding
	 * @param bytes bytes to convert
	 * @param bytesLen bytes length
	 * @return the string created
	 */
	public static String fromBytes(byte[] bytes, int bytesLen)
	{
		try
		{
			return new String(bytes, 0, bytesLen, RequestSerializer.DFL_CHARSET_STR);
		}
		catch (Exception ex)
		{
			return "";
		}
	}
}
